const app = getApp();
import {
    request
} from './request.js';
const {
    getWeixinUser,
    getUserNameByToken,
    getUserInfoByToken
} = require('../config.js')

const isEmptyObject = (e) => {
    var t;
    for (t in e)
        return !1;
    return !0
}

const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}

const isEmpty = string => {
    return string === '' || string === null || string === undefined;
}

const getCommentContent = string => {
    if (isEmpty(string)) {
        return '此用户没有填写评论内容^_^'
    } else {
        return string
    }
}

const getString = string => {
    if (string == '') {
        return '不详';
    } else
        return string;
}

const getNickName = string => {
    if (string == '') {
        return '匿名用户';
    } else
        return string;
}

const getOpenTimeString = (openTime, closeTime) => {
    if (openTime == '' || closeTime == '') {
        return '不详';
    } else if (openTime == '00:00' && closeTime == '24:00') {
        return '全天'
    } else
        return openTime + '~' + closeTime
}

const getChargeString = charge => {
    if (charge == '') {
        return '不详';
    } else if (charge == 0) {
        return '免费'
    } else
        return charge + "元/次"
}

function formatLocation(longitude, latitude) {
    if (typeof longitude === 'string' && typeof latitude === 'string') {
        longitude = parseFloat(longitude)
        latitude = parseFloat(latitude)
    }

    longitude = longitude.toFixed(2)
    latitude = latitude.toFixed(2)

    return {
        longitude: longitude.toString().split('.'),
        latitude: latitude.toString().split('.')
    }
}
// 去前后空格
function trim(str) {
    return str.replace(/(^\s*)|(\s*$)/g, "");
}

// 提示错误信息
function isError(msg, that) {
    that.setData({
        showTopTips: true,
        errorMsg: msg
    })
    setTimeout(function() {

            that.setData({
                showTopTips: false,
                errorMsg: ""
            })

            //要延时执行的代码
        }, 2000) //延迟时间 这里是1秒
}

// 清空错误信息
function clearError(that) {
    that.setData({
        showTopTips: false,
        errorMsg: ""
    })
}

function debounce(func, wait, immediate) {
    // immediate默认为false
    var timeout, args, context, timestamp, result;

    var later = function() {
        // 当wait指定的时间间隔期间多次调用_.debounce返回的函数，则会不断更新timestamp的值，导致last < wait && last >= 0一直为true，从而不断启动新的计时器延时执行func
        var last = new Date() - timestamp;

        if (last < wait && last >= 0) {
            timeout = setTimeout(later, wait - last);
        } else {
            timeout = null;
            if (!immediate) {
                result = func.apply(context, args);
                if (!timeout) context = args = null;
            }
        }
    };

    return function() {
        context = this;
        args = arguments;
        timestamp = new Date();
        // 第一次调用该方法时，且immediate为true，则调用func函数
        var callNow = immediate && !timeout;
        // 在wait指定的时间间隔内首次调用该方法，则启动计时器定时调用func函数
        if (!timeout) timeout = setTimeout(later, wait);
        if (callNow) {
            result = func.apply(context, args);
            context = args = null;
        }
        return result;
    };
};

function needPermission(todo) {
    this.isLogin().then(({
        isLogin
    }) => {
        if (isLogin) {
            todo();
        } else {
            this.showLoginDialog();
        }
    })
}

function isLogin() {
    const token = wx.getStorageSync('token');

    return new Promise((resolve, reject) => {
        request({
            url: getUserInfoByToken,
            header: {
                token
            },
            data: {
                token
            }
        }).then(data => {
            let isLogin = false;
            let bindPhone = false;
            if (data.code === '0') {
                const {
                    code,
                    msg,
                    nickname,
                    wxPhoneNumber
                } = data.user;
                console.log(`isLogin = ${!this.isEmpty(nickname)}`)
                isLogin = !this.isEmpty(nickname);
                bindPhone = !this.isEmpty(wxPhoneNumber);
            }

            resolve({
                isLogin,
                bindPhone,
                user: data.user
            });
        })
    });
}

function showLoginDialog() {
    wx.showModal({
        title: '用户信息未授权',
        content: '如需正常使用找公厕功能，需要获得您的用户信息及电话绑定，请点按确定。进入信息授权页面。',
        showCancel: false,
        success: function(res) {
            if (res.confirm) {
                console.log('用户点击确定')
                wx.navigateTo({
                    url: '../register/register'
                })
            }
        }
    })
}

module.exports = {
    isError,
    clearError,
    trim,
    formatTime,
    getChargeString,
    getOpenTimeString,
    getNickName,
    getCommentContent,
    getString,
    isEmpty,
    formatLocation,
    debounce,
    isLogin,
    showLoginDialog,
    needPermission
}